﻿using Hd.AbpCoding.Permissions;
using Hd.AbpCoding.Projects.Dtos;
using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Dtos;

namespace Hd.AbpCoding.Projects
{

    [Authorize(AbpCodingPermissions.DomainDesc.Default)]
    public class DomainDescAppService : AbpCodingAppService, IDomainDescAppService
    {

        protected IDomainDescManager DomainDescManager { get; }
        protected IDomainDescRepository Repository { get; }
        public DomainDescAppService(
            IDomainDescManager domainDescManager,
            IDomainDescRepository domainDescRepository)
        {
            Repository = domainDescRepository;
            DomainDescManager = domainDescManager;
        }

        [Authorize(AbpCodingPermissions.DomainDesc.Create)]
        public async Task<DomainDescDto> CreateAsync(CreateDomainDescDto input)
        {
            if (!await DomainDescManager.CheckNameAsync(input.ProjectId, input.Name))
            {
                throw new UserFriendlyException(L["NameAlreadyExisted", input.Name]);
            }

            var domainDesc = new DomainDesc(GuidGenerator.Create(), input.ProjectId, input.Name, input.PrimaryKeyType, input.IsAggregateRoot, input.EnableMultiTenant, input.Path, input.Description, input.Audited);
            domainDesc = await Repository.InsertAsync(domainDesc);
            return MapDto(domainDesc);
        }

        private DomainDescDto MapDto(DomainDesc domainDesc)
        {
            return ObjectMapper.Map<DomainDesc, DomainDescDto>(domainDesc);
        }

        [Authorize(AbpCodingPermissions.DomainDesc.Delete)]
        public async Task DeleteAsync(Guid id)
        {
            await Repository.DeleteAsync(id);
        }

        public async Task<DomainDescDto> GetAsync(Guid id)
        {
            var domainDesc = await Repository.GetAsync(id);
            return MapDto(domainDesc);
        }

        public Task<PagedResultDto<DomainDescDto>> GetListAsync(GetDomainDescsInput input)
        {
            throw new NotImplementedException();
        }

        [Authorize(AbpCodingPermissions.DomainDesc.Update)]
        public async Task<DomainDescDto> UpdateAsync(Guid id, UpdateDomainDescDto input)
        {
            var domainDesc = await Repository.GetAsync(id);
            if (!await DomainDescManager.CheckNameAsync(input.ProjectId, input.Name, id))
            {
                throw new UserFriendlyException(L["NameAlreadyExisted", input.Name]);
            }
            domainDesc.Update(input.ProjectId, input.Name, input.PrimaryKeyType, input.IsAggregateRoot, input.EnableMultiTenant, input.Path, input.Description, input.Audited);
            await Repository.UpdateAsync(domainDesc);
            return MapDto(domainDesc);
        }
    }
}
